1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.annotations.GwtIncompatible;
23
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.util.EnumMap;
28 import java.util.HashMap;
29 import java.util.Map;
30
31 import javax.annotation.Nullable;
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 @GwtCompatible(emulated = true)
47 public final class EnumHashBiMap<K extends Enum<K>, V>
48 extends AbstractBiMap<K, V> {
49 private transient Class<K> keyType;
50
51
52
53
54
55
56 public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
57 create(Class<K> keyType) {
58 return new EnumHashBiMap<K, V>(keyType);
59 }
60
61
62
63
64
65
66
67
68
69
70
71 public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
72 create(Map<K, ? extends V> map) {
73 EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
74 bimap.putAll(map);
75 return bimap;
76 }
77
78 private EnumHashBiMap(Class<K> keyType) {
79 super(WellBehavedMap.wrap(
80 new EnumMap<K, V>(keyType)),
81 Maps.<V, K>newHashMapWithExpectedSize(
82 keyType.getEnumConstants().length));
83 this.keyType = keyType;
84 }
85
86
87
88 @Override
89 K checkKey(K key) {
90 return checkNotNull(key);
91 }
92
93 @Override public V put(K key, @Nullable V value) {
94 return super.put(key, value);
95 }
96
97 @Override public V forcePut(K key, @Nullable V value) {
98 return super.forcePut(key, value);
99 }
100
101
102 public Class<K> keyType() {
103 return keyType;
104 }
105
106
107
108
109
110 @GwtIncompatible("java.io.ObjectOutputStream")
111 private void writeObject(ObjectOutputStream stream) throws IOException {
112 stream.defaultWriteObject();
113 stream.writeObject(keyType);
114 Serialization.writeMap(this, stream);
115 }
116
117 @SuppressWarnings("unchecked")
118 @GwtIncompatible("java.io.ObjectInputStream")
119 private void readObject(ObjectInputStream stream)
120 throws IOException, ClassNotFoundException {
121 stream.defaultReadObject();
122 keyType = (Class<K>) stream.readObject();
123 setDelegates(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
124 new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
125 Serialization.populateMap(this, stream);
126 }
127
128 @GwtIncompatible("only needed in emulated source.")
129 private static final long serialVersionUID = 0;
130 }